package com.hxbd.test.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Assert;

import com.duan.test.utils.common.CommonUtils;
import com.hxbd.test.handles.PageElementHandler;

public class ReadDBConfigFromXml {
	static Element root;
    static Document document = null;
    private static final String DBFILE__PATH = "DBFILE__PATH";
	static {
		//创建SAXReader对象  
	    SAXReader reader = new SAXReader();  
	    //读取文件 转换成Document  
	    try {
			document = reader.read(CommonUtils.getFilePath(PageElementHandler.getStoreSettingProperties().getProperty(DBFILE__PATH)));
//			document = reader.read(CommonUtils.getFilePath("DB.xml"));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  		
		//获取根节点元素对象  
	    root = document.getRootElement();  
	}
	/**
	 * 获得db配置
	 * @return
	 */
	public static Map<String,List<Map<String,Object>>> readDbConfig() {
		Map<String,List<Map<String,Object>>> map = new HashMap<>();
		for (Element e : root.elements()) {
			List<Map<String,Object>> ls = new ArrayList<>();
			String env = e.getName();
			for (Element ee : e.elements("dbgorup")) {
				Map<String,Object> m = new HashMap<String,Object>();
				m.put("synchronized", Boolean.parseBoolean(ee.attributeValue("synchronized")));				
				List<Element> ll = ee.elements("db");
				List<Map<String,String>> dblist = new ArrayList<>();
				for (Element el : ll) {
					if (null == el.attributeValue("enable") || !el.attributeValue("enable").equalsIgnoreCase("false")) {
						Map<String,String> m2 = new HashMap<String,String>();
						for (Element dbconf : el.elements()) {
							m2.put(dbconf.getName(), dbconf.attributeValue("value"));
						}
						dblist.add(m2);
					}				
				}
				m.put("data", dblist);
				ls.add(m);					
			}
			map.put(env, ls);
		}
		return map;
	}
}
